package com.buobao.reflect.demo;

import com.buobao.reflect.demo.entity.Employee;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * 反射获取成员变量
 */
public class FieldSample {
    public static void main(String[] args) {
        try {
            Class employeeClass = Class.forName("com.buobao.reflect.demo.entity.Employee");
            Constructor constructor = employeeClass.getConstructor(new Class[]{int.class,String.class,float.class,String.class, Date.class});
            Employee employee = (Employee) constructor.newInstance(new Object[]{1002,"lisi",3500,"designer",new Date()});
            System.out.println(employee);

            //这里如果是公有变量则可以直接用getField获取
            Field enoField = employeeClass.getDeclaredField("eno");
            enoField.setAccessible(true);
            System.out.println(enoField.get(employee));
            enoField.set(employee,999);
            System.out.println(employee);
            //其他成员访问类似
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
}
